package vn.easyforshopping.res;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;

public class SDCardWriter implements Runnable {

	ArrayList<Image> imageList = new ArrayList<Image>();
	/**
	 * Image hien thoi dang xu li de ghi xuong file.
	 */
	Image imageExecuting = null;
	private String path;
	
	public SDCardWriter(String path) {
		this.path = path;
	}
	
	@Override
	public void run() {
		while (!this.imageList.isEmpty()) {
			imageExecuting = this.imageList.get(0);
			this.imageList.remove(0);
			writeBitmapToSDCard(imageExecuting.link, imageExecuting.bitmap);
		}
	}
	
	public void writeBitmap(String webLink, Bitmap b) {
		addBitmapToWrite(new Image(webLink, b));
	}
	
	public void writeImage(Image image) {
		addBitmapToWrite(image);
	}
	
	private void addBitmapToWrite(Image image) {
		synchronized (this.imageList) {
			this.imageList.add(image);
			this.imageList.notifyAll();
			return;
		}		
	}
	
	private void writeBitmapToSDCard(String webLink, Bitmap b) {
		if (b != null) {
//			String root = Environment.getExternalStorageDirectory().toString();root + "/EasyForShooping"
			File myDir=new File(path);
            myDir.mkdir();
            
            File file = new File (myDir, webLink);
            //Neu file da co ui thi xoa no di.
            if (file.exists ()) file.delete (); 
            try {
                   FileOutputStream out = new FileOutputStream(file);
                   b.compress(CompressFormat.PNG, 600, out);
                   out.flush();
                   out.close();
            } catch (Exception e) {
                   e.printStackTrace();
            }
		}
	}

}
